package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.model.admin.dtos.ChannelDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {

    @Override
    public ResponseResult findByNameAndPage(ChannelDto channelDto) {
        //参数校验
        if (channelDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //设置分页条件
        //初始化分页操作
        channelDto.checkParam();
        Page<AdChannel> page = new Page<>(channelDto.getPage(),channelDto.getSize());
        //设置查询条件
        String name = channelDto.getName();
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper();
        if (!StringUtils.isEmpty(name)){
            queryWrapper.like(AdChannel::getName,name);
        }
        //执行查询
        IPage<AdChannel> resultPage = page(page, queryWrapper);
        ResponseResult responseResult = new PageResponseResult(channelDto.getPage(),channelDto.getSize(),resultPage.getTotal());
        //返回当前页结果集
        responseResult.setData(resultPage.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult delete(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //有效状态的频道不能删除
        AdChannel adChannel = getById((id));
        Boolean status = adChannel.getStatus();
        if (status){
            return ResponseResult.errorResult(AppHttpCodeEnum.CHANNEL_INVALID_STATUS);
        }

        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
